import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:furaha_mkopo/commonTool/fm_language_tool.dart';
import 'package:furaha_mkopo/commonUI/fm_progress_hud.dart';
import 'package:furaha_mkopo/commonUI/fm_toast.dart';
import 'package:furaha_mkopo/page/authentication/api/fm_auth_confirm_info_api.dart';
import 'package:furaha_mkopo/page/authentication/entity/fm_identity_authentication_entity.dart';
import 'package:furaha_mkopo/page/authentication/enum/fm_auth_select_enum.dart';
import 'package:furaha_mkopo/page/authentication/enum/fm_auth_update_info_enum.dart';
import 'package:furaha_mkopo/page/dialog/time/fm_select_time_page.dart';

class FMAuthInfoConfirmDialog extends StatefulWidget {
  FMAuthImageResultEntity resultEntity;
  String listen;
  Function() onConfirm;
  String cardType;
  FMAuthInfoConfirmDialog({super.key, required this.resultEntity,required this.listen,required this.onConfirm,required this.cardType});

  @override
  State<FMAuthInfoConfirmDialog> createState() =>
      _FMAuthInfoConfirmDialogState();
}

class _FMAuthInfoConfirmDialogState extends State<FMAuthInfoConfirmDialog> {
  FMAuthUpdateInfoEnum _updateInfoEnum = FMAuthUpdateInfoEnum.none;
  TextEditingController nameController = TextEditingController();
  TextEditingController idNumberController = TextEditingController();
  TextEditingController controller1 = TextEditingController();
  TextEditingController controller2 = TextEditingController();
  TextEditingController controller3 = TextEditingController();
  TextEditingController controller4 = TextEditingController();
  FocusNode focusNode1 = FocusNode();
  FocusNode focusNode2 = FocusNode();
  FocusNode focusNode3 = FocusNode();
  FocusNode focusNode4 = FocusNode();
  @override
  void initState() {
    super.initState();
    nameController.text = getValue("planned");
    idNumberController.text = getValue("succeed");
  }
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {

      },
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: GestureDetector(
          onTap: () {},
          child: Stack(
            children: [
              Center(
                child: Visibility(
                  visible: _updateInfoEnum == FMAuthUpdateInfoEnum.none,
                  child: Container(
                    width: 311,
                    height: 521,
                    alignment: Alignment.topCenter,
                    decoration: const BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage(
                            'assets/authentication/ic_auth_confirm_bg.png'),
                        fit: BoxFit.fill,
                      ),
                    ),
                    child: Column(
                      children: [
                        const SizedBox(
                          height: 18.14,
                        ),
                        Text(
                          FMLanguageTool.getText("Please confirm"),
                          style: const TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.w700,
                              color: Color(0xFF333333)),
                        ),
                        Container(
                          width: 287,
                          height: 345,
                          margin: const EdgeInsets.only(
                              top: 9.86, left: 12, right: 12),
                          child: Column(
                            children: [
                              const SizedBox(height: 20,),
                              generateNameOrIDNumber(getTitle("planned"), nameController,null,null),
                              if(widget.cardType == FMAuthSelectEnum.other.title)
                                generateBirthday(getTitle("courtyard"), getValue("courtyard")),
                              generateNIDAOrVoterOrOther(getTitle("succeed")),
                              if(widget.cardType != FMAuthSelectEnum.other.title)
                                generateBirthday(getTitle("courtyard"), getValue("courtyard")),
                              generateBottomTip()
                            ],
                          ),
                        ),
                        generateConfirmBtn(),
                        generateCancelBtn(context),
                      ],
                    ),
                  ),
                ),
              ),
              Center(
                  child: Visibility(
                visible: _updateInfoEnum == FMAuthUpdateInfoEnum.birthday,
                child: FMSelectTimePage(
                  time: widget.resultEntity.portland?[2].hearts,
                  onBack: onBirthdayCancel,
                  onConfirm: onBirthdayConfirm,
                ),
              ))
            ],
          ),
        ),
      ),
    );
  }

  Widget generateNameOrIDNumber(
      String title,
      TextEditingController editingController,
      TextInputType? keyboardType,
      List<TextInputFormatter>? inputFormatters) {
    return Container(
      width: 263,
      height: 74,
      decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(10)),
          color: Color(0xFFFFEFDC)),
      padding: const EdgeInsets.only(left: 12, right: 12),
      margin: const EdgeInsets.only(top: 8),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: const TextStyle(
              height: 1,
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Color(0xFF333333)),
          ),
          const SizedBox(height: 12,),
          TextField(
            controller: editingController,
            decoration: const InputDecoration(
              isDense: true,
              border: InputBorder.none,
              contentPadding: EdgeInsets.zero, // 清除内边距
              focusedBorder: InputBorder.none, // 聚焦状态边框
              enabledBorder: InputBorder.none,
              counterText: ""
            ),
            maxLines: 1,
            keyboardType: keyboardType,
            inputFormatters: inputFormatters,
            style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
                color: Color(0xFF333333)),
          ),
        ],
      ),
    );
  }

  Widget generateNIDAOrVoterOrOther(String title){
    if(widget.cardType == FMAuthSelectEnum.nida.title){
      return generateNIDA(title, controller1, controller2, controller3,
          controller4, focusNode1, focusNode2, focusNode3, focusNode4);
    }else if(widget.cardType == FMAuthSelectEnum.voter.title){
      return generateVoter(title, controller1, controller2, controller3,
          controller4, focusNode1, focusNode2, focusNode3, focusNode4);
    }else{
      return generateNameOrIDNumber(title, idNumberController,TextInputType.number,[FilteringTextInputFormatter.digitsOnly]);
    }
  }

  Widget generateNIDA(
      String title,
      TextEditingController controller1,
      TextEditingController controller2,
      TextEditingController controller3,
      TextEditingController controller4,
      FocusNode focusNode1,
      FocusNode focusNode2,
      FocusNode focusNode3,
      FocusNode focusNode4) {
    return Container(
      width: 263,
      height: 74,
      decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(10)),
          color: Color(0xFFFFEFDC)),
      padding: const EdgeInsets.only(left: 12, right: 12),
      margin: const EdgeInsets.only(top: 8),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: const TextStyle(
                height: 1,
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Color(0xFF333333)),
          ),
          const SizedBox(height: 12,),
          Row(
            children: [
              generateIDNumber(70, 30, 8, controller1,focusNode1),
              generateCross(),
              generateIDNumber(48, 30, 5, controller2,focusNode2),
              generateCross(),
              generateIDNumber(48, 30, 5, controller3,focusNode3),
              generateCross(),
              generateIDNumber(30, 30, 2, controller4,focusNode4)
            ],
          ),

        ],
      ),
    );
  }

  Widget generateVoter(
      String title,
      TextEditingController controller1,
      TextEditingController controller2,
      TextEditingController controller3,
      TextEditingController controller4,
      FocusNode focusNode1,
      FocusNode focusNode2,
      FocusNode focusNode3,
      FocusNode focusNode4) {
    return Container(
      width: 264,
      height: 74,
      decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(10)),
          color: Color(0xFFFFEFDC)),
      padding: const EdgeInsets.only(left: 12, right: 12),
      margin: const EdgeInsets.only(top: 8),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: const TextStyle(
                height: 1,
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Color(0xFF333333)),
          ),
          const SizedBox(height: 12,),
          Row(
            children: [
              const Text("T", style: TextStyle(fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF333333)),),
              generateCross(margin: 0),
              generateIDNumber(69, 30, 4, controller1,focusNode1),
              generateCross(margin: 0),
              generateIDNumber(48, 30, 4, controller2,focusNode2),
              generateCross(margin: 0),
              generateIDNumber(48, 30, 3, controller3,focusNode3),
              generateCross(margin: 0),
              generateIDNumber(30, 30, 1, controller4,focusNode4)
            ],
          ),

        ],
      ),
    );
  }

  Widget generateIDNumber(double width, double height, int maxLength,
      TextEditingController editingController,FocusNode focusNode) {
    return Container(
      width: width,
      height: height,
      padding: const EdgeInsets.only(right: 8, left: 8, top: 6, bottom: 6),
      decoration: BoxDecoration(
          borderRadius: const BorderRadius.all(Radius.circular(9)),
          color: Colors.white,
          border: Border.all(color: const Color(0xFFFFD19B), width: 1)),
      child: TextField(
        controller: editingController,
        onChanged: (text){
          if(widget.cardType == FMAuthSelectEnum.nida.title){
            if(text.length == 8){
              String year = editingController.text.substring(0,4);
              String month = editingController.text.substring(4,6).padLeft(2,"0");
              String day = editingController.text.substring(6,8).padLeft(2,"0");
              onBirthdayConfirm("$day-$month-$year");
            }
          }
          if(editingController == controller1 && text.length == maxLength){
            focusNode2.requestFocus();
          }else if(editingController == controller2 && text.length == maxLength){
            focusNode3.requestFocus();
          }else if(editingController == controller3 && text.length == maxLength){
            focusNode4.requestFocus();
          }
        },
        decoration: const InputDecoration(
            isDense: true,
            border: InputBorder.none,
            contentPadding: EdgeInsets.zero,
            // 清除内边距
            focusedBorder: InputBorder.none,
            // 聚焦状态边框
            enabledBorder: InputBorder.none,
            counterText: ""),
        maxLines: 1,
        keyboardType: TextInputType.number,
        inputFormatters: [
          FilteringTextInputFormatter.digitsOnly
        ],
        focusNode: focusNode,
        maxLength: maxLength,
        style: const TextStyle(
            fontSize: 13,
            fontWeight: FontWeight.w500,
            color: Color(0xFF333333)),
      ),
    );
  }

  Widget generateCross({double margin = 3}){
    return Container(
        margin: EdgeInsets.only(left: margin, right: margin),
        child: const Text(
          "-",
          style: TextStyle(
              fontWeight: FontWeight.w500,
              color: Color(0xFFCCCCCC)),
        ));
  }

  Widget generateBirthday(String title,String value){
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        setState(() {
          _updateInfoEnum = FMAuthUpdateInfoEnum.birthday;
        });
      },
      child: Container(
        width: 263,
        height: 74,
        decoration: const BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(10)),
            color: Color(0xFFFFEFDC)),
        margin: const EdgeInsets.only(top: 8),
        padding: const EdgeInsets.only(left: 12, right: 12),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                  color: Color(0xFF333333)),
            ),
            const SizedBox(
              height: 12,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  value,
                  style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      color: Color(0xFF333333)),
                ),
                Image.asset(
                  "assets/authentication/ic_auth_confirm_down.png",
                  width: 16,
                  height: 16,
                )
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget generateBottomTip(){
    return Container(
      alignment: Alignment.center,
      margin: const EdgeInsets.only(top: 8, left: 12, right: 12),
      child: Text(
        widget.resultEntity.stone ?? "",
        textAlign: TextAlign.center,
        style: const TextStyle(
            fontSize: 12,
            fontWeight: FontWeight.w500,
            color: Color(0xFFF14857)),
      ),
    );
  }

  Widget generateConfirmBtn() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        onConfirm();
      },
      child: Container(
        margin: const EdgeInsets.only(top: 40, left: 20, right: 20),
        height: 47,
        width: double.infinity,
        alignment: Alignment.center,
        decoration: const BoxDecoration(
          color: Color(0xFF000000),
          borderRadius: BorderRadius.all(Radius.circular(8)),
          image: DecorationImage(
            image: AssetImage('assets/address/ic_address_arrow.png'),
          ),
        ),
        child: const Text(
          'Confirm',
          style: TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.w700,
          ),
        ),
      ),
    );
  }

  Widget generateCancelBtn(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        Navigator.of(context).pop();
      },
      child: Container(
        margin: const EdgeInsets.only(top: 10),
        alignment: Alignment.center,
        child: const Text(
          'Cancel',
          style: TextStyle(
            color: Color(0xFF333333),
            fontSize: 16,
          ),
        ),
      ),
    );
  }

  void onBirthdayCancel() {
    setState(() {
      _updateInfoEnum = FMAuthUpdateInfoEnum.none;
    });
  }

  void onBirthdayConfirm(String time) {
    widget.resultEntity.courtyard = time;
    widget.resultEntity.portland?[2].hearts = time;
    setState(() {
      _updateInfoEnum = FMAuthUpdateInfoEnum.none;
    });
  }

  String getTitle(String key){
    List<FMAuthImagePortLandEntity> list = widget.resultEntity.portland??[];
    for (var element in list) {
      if (element.cheers == key) {
        return element.harder??"--";
      }
    }
    return "--";
  }

  String getValue(String key){
    List<FMAuthImagePortLandEntity> list = widget.resultEntity.portland??[];
    for (var element in list) {
      if (element.cheers == key) {
        return element.hearts??"--";
      }
    }
    return "--";
  }

  void onConfirm() {
    String courtyard = widget.resultEntity.courtyard??"";
    String succeed = "";
    if(widget.cardType == FMAuthSelectEnum.nida.title){
      succeed = controller1.text.toString() +
          controller2.text.toString() +
          controller3.text.toString() +
          controller4.text.toString();
    }else if(widget.cardType == FMAuthSelectEnum.voter.title){
      succeed = controller1.text.toString() +
          controller2.text.toString() +
          controller3.text.toString() +
          controller4.text.toString();
    }else {
      succeed = idNumberController.text.toString();
    }
    String planned = nameController.text.toString();
    FMAuthConfirmInfoApi infoApi = FMAuthConfirmInfoApi(
        courtyard: courtyard,
        succeed: succeed,
        planned: planned,
        listen: widget.listen,
        card_type: widget.cardType);
    FMProgressHud.showLoading();
    infoApi.send().then((value){
      FMProgressHud.hideLoading();
      if(value.code == null || value.code != 0){
        FMToast.showText(value.message??"Network request error");
        return;
      }
      widget.onConfirm();
      Navigator.pop(context);
    });

  }
}
